﻿using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace ManageSystemClient.HttpService
{
    public class HttpServiceBase
    {
        private readonly HttpClient client;

        public HttpServiceBase()
        {
            var setting = Properties.Settings.Default;
            client = new()
            {
                Timeout = TimeSpan.FromSeconds(setting.Timeout),
                BaseAddress = new(setting.BaseAddress)
            };
        }

        public async Task SendAsync(string? url, HttpMethod method, object? data = default)
        {
            var request = new HttpRequestMessage(method, url)
            {
                Content = JsonContent.Create(data),
            };
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
        }

        public async Task<T> SendAsync<T>(string? url, HttpMethod method, object? data = default) where T : notnull
        {
            var request = new HttpRequestMessage(method, url)
            {
                Content = JsonContent.Create(data)
            };
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            var receive = await response.Content.ReadFromJsonAsync<T>();
            if (receive == null)
            {
                throw new NullReferenceException("The response body is null.");
            }
            return receive;
        }

        public void Authorize(string? token)
        {
            client.DefaultRequestHeaders.Authorization = new("Bearer", token);
        }
    }
}
